/**
 * VoicePlayingAnimation - 语音播放动画组件
 *
 * 展示三个波动的竖条，模拟语音播放效果
 *
 * 特性：
 * - 基于 useFrameAnimationController 实现
 * - 支持自定义颜色、尺寸
 * - 支持外部控制播放/停止
 * - 循环播放
 *
 * @example
 * ```tsx
 * <VoicePlayingAnimation
 *   playing={isPlaying}
 *   color="#007AFF"
 *   size="medium"
 * />
 * ```
 */

import React, { useMemo, useEffect } from 'react';
import { View, Animated, Easing, StyleSheet } from 'react-native';
import { useFrameAnimationController } from '../../hooks/useFrameAnimationController';

/**
 * 组件属性
 */
export interface VoicePlayingAnimationProps {
  /** 是否播放，默认 false */
  playing?: boolean;

  /** 颜色，默认 '#007AFF' */
  color?: string;

  /** 预设尺寸，默认 'medium' */
  size?: 'small' | 'medium' | 'large';

  /** 自定义竖条宽度（覆盖 size） */
  barWidth?: number;

  /** 自定义最大高度（覆盖 size） */
  maxHeight?: number;

  /** 自定义间距（覆盖 size） */
  gap?: number;

  /** 每帧持续时间（毫秒），默认 200 */
  frameDuration?: number;
}

/**
 * 预设尺寸配置
 */
const SIZE_PRESETS = {
  small: { barWidth: 2, maxHeight: 16, minHeight: 6, gap: 3 },
  medium: { barWidth: 3, maxHeight: 24, minHeight: 8, gap: 4 },
  large: { barWidth: 4, maxHeight: 32, minHeight: 10, gap: 5 },
};

/**
 * 语音播放动画组件
 */
export function VoicePlayingAnimation({
  playing = false,
  color = '#007AFF',
  size = 'medium',
  barWidth: customBarWidth,
  maxHeight: customMaxHeight,
  gap: customGap,
  frameDuration = 200,
}: VoicePlayingAnimationProps) {
  // 3. 定义帧数据（归一化到 0-1）
  const frameData = useMemo(
    () => ({
      bar1Height: [3, 6, 10],
      bar2Height: [6, 10, 5],
      bar3Height: [10, 4, 7],
    }),
    [],
  );
  // 1. 计算尺寸
  const preset = SIZE_PRESETS[size];
  const barWidth = customBarWidth ?? preset.barWidth;
  const maxHeight = customMaxHeight ?? preset.maxHeight;
  // const minHeight = preset.minHeight;
  const gap = customGap ?? preset.gap;

  // 2. 使用 Hook
  const {
    animatedValue,
    registerAnimation,
    interpolations,
    play,
    stop,
    isPlaying,
  } = useFrameAnimationController({ frameData, frameCount: 3 });

  // 4. 创建并注册对象（只在 frameDuration 变化时重建）
  useEffect(() => {
    // 创建循环动画
    const animation = Animated.loop(
      Animated.timing(animatedValue, {
        toValue: 2, // 3帧：0, 1, 2
        duration: frameDuration * 3,
        easing: Easing.linear,
        useNativeDriver: false, // height 不支持原生驱动
      }),
    );

    registerAnimation(animation);
  }, [frameDuration, animatedValue, registerAnimation]); // 依赖配置项

  // 5. 响应外部 playing prop
  useEffect(() => {
    console.log('playing', playing, 'isPlaying', isPlaying);
    if (playing && !isPlaying) {
      play();
    } else if (!playing && isPlaying) {
      stop();
    }
  }, [playing, isPlaying, play, stop]);

  // 6. 渲染
  if (!interpolations) {
    return null; // 等待 interpolations 注册
  }

  return (
    <View
      style={[
        styles.container,
        {
          gap,
          height: maxHeight,
        },
      ]}
    >
      <Animated.View
        style={{
          width: barWidth,
          backgroundColor: color,
          borderRadius: barWidth / 2,
          height: interpolations.bar1Height,
        }}
      />
      <Animated.View
        style={{
          width: barWidth,
          backgroundColor: color,
          borderRadius: barWidth / 2,
          height: interpolations.bar2Height,
        }}
      />
      <Animated.View
        style={{
          width: barWidth,
          backgroundColor: color,
          borderRadius: barWidth / 2,
          height: interpolations.bar3Height,
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'flex-end',
  },
});
